﻿using System;
using System.Data;
using System.Data.Linq;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Xml.Linq;
using Hisun.Models;

namespace Hisun.Controllers
{

    /// <summary>
    /// Copyright (C) 2008 HOHO``
    /// All rights reserved
    /// NameSpace:Hisun.Controllers.AbcCostCenterItems
    /// Description :成本细项数据操作
    /// 
    /// CostItemsID:成本细项ID
    /// CostItemID:成本细项条目ID
    /// 
    /// Created By QiuZhongJie At 2008/10/15 8:10
    /// </summary>
    public class AbcCostCenterItems
    {

        private HisunDBDataContext db = new HisunDBDataContext();
        private bool isUseGlobal;
        private string lastError;
        private string accountPeriod;
        private string costItemBrevityCode;

        public string LastError
        {
            get { return lastError; }
            set { lastError = value; }
        }



        /// <summary>
        /// Initializes a new instance of the <see cref="AbcCostCenterItems"/> class.
        /// </summary>
        /// <param name="accountPeriod">The account period.</param>
        /// <param name="costItemBrevityCode">The cost item brevity code.</param>
        public AbcCostCenterItems(string accountPeriod, string costItemBrevityCode)
        {
            this.accountPeriod = accountPeriod;//会计期间
            this.costItemBrevityCode = costItemBrevityCode;//成本细项简码
            isUseGlobal = true;
        }

        /// <summary>
        /// Gets all items.
        /// </summary>
        /// <returns></returns>
        public IQueryable<TABC_JC_CostCenterItems> GetAllItems()
        {
            var items = (from c in db.TABC_JC_CostCenterItems
                         where c.会计期间ID == accountPeriod
                         && c.成本细项ID == costItemBrevityCode
                         select c);
            return items;
        }

        /// <summary>
        /// Gets the items by cost center ID.
        /// </summary>
        /// <param name="costCenterID">The cost center ID.</param>
        /// <returns></returns>
        public IQueryable<TABC_JC_CostCenterItems> GetItemsByCostCenterID(int costCenterID)
        {
            var items = (from c in db.TABC_JC_CostCenterItems
                         where c.作业中心ID == costCenterID
                         && c.成本细项ID == costItemBrevityCode
                         && c.会计期间ID == accountPeriod
                         select c);
            return items;
        }



        /// <summary>
        /// Gets the name of the items by cost center.
        /// </summary>
        /// <param name="costCenterName">Name of the cost center.</param>
        /// <returns></returns>
        public IQueryable<TABC_JC_CostCenterItems> GetItemsByCostCenterName(string costCenterName)
        {
            int costCenterID = db.TABC_JS_CostCenter.Where(c => c.作业中心名称.Contains(costCenterName)).Select(c => c.作业中心ID).Single();
            var items = (from c in db.TABC_JC_CostCenterItems
                         where c.作业中心ID == costCenterID
                         && c.成本细项ID == costItemBrevityCode
                         && c.会计期间ID == accountPeriod
                         select c);
            return items;
        }


        /// <summary>
        /// Gets the item.
        /// </summary>
        /// <param name="costCenterItemID">The cost center item ID.</param>
        /// <returns></returns>
        public TABC_JC_CostCenterItems GetItem(int costCenterItemID)
        {
            return db.TABC_JC_CostCenterItems.Where(c => c.ID == costCenterItemID).Single();
        }



        /// <summary>
        /// Updates the item.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <returns></returns>
        public int UpdateItem(TABC_JC_CostCenterItems item)
        {
            var oldItem = (from c in db.TABC_JC_CostCenterItems
                           where c.ID == item.ID
                           select c).Single();
            oldItem = item;
            try
            {
                db.SubmitChanges(ConflictMode.FailOnFirstConflict);
            }
            catch
            {
                return -1;
            }
            return 0;
        }

        /// <summary>
        /// Updates the price.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <param name="price">The price.</param>
        /// <returns></returns>
        public int UpdatePrice(int id, decimal price)
        {
            try
            {
                var oldItem = (from c in db.TABC_JC_CostCenterItems
                               where c.ID == id
                               select c).Single();
                oldItem.金额 = price;
                db.SubmitChanges();
            }
            catch (Exception ex)
            {
                lastError = ex.Message;
                return -1;
            }
            return 0;
        }


        /// <summary>
        /// Does the search.
        /// </summary>
        /// <param name="searchType">Type of the search.</param>
        /// <param name="searchKey">The search key.</param>
        /// <returns></returns>
        public IQueryable<TABC_JC_CostCenterItems> DoSearch(string searchType, string searchKey)
        {
            if (!isUseGlobal)
                throw new Exception("没有限定的条件请使用扩展查询");
            switch (searchType)
            {
                case "CostCenterID":
                    return GetItemsByCostCenterID(Convert.ToInt32(searchKey));
                case "CostCenterName":
                    return GetItemsByCostCenterName(searchKey);
                default:
                    return null;
            }
        }



        public IQueryable<TABC_JC_CostCenterItems> DoSearchExt(string searchType, string searchKey, string accountPeriod)
        {
            return null;
        }


        /// <summary>
        /// Checks the data set.
        /// </summary>
        /// <param name="xlsData">The XLS data.</param>
        /// <returns></returns>
        public bool CheckDataSet(DataSet xlsData)
        {

            return false;
        }


        /// <summary>
        /// 导入XLS的DT数据到SQL中
        /// </summary>
        /// <param name="xlsDataTable">The XLS data table.</param>
        /// <param name="costItemsID">The cost items ID.</param>
        /// <returns></returns>
        public int ImportDataTableToSQL(DataTable xlsDataTable, string costItemsID)
        {
            int posiCostCenterID = -1;
            int posiMoneyValue = -1;
            int costItemID = -1;

            if (xlsDataTable == null)
                throw new Exception("给出的数据表为NULL!");
            for (int i = 0; i < xlsDataTable.Columns.Count; i++)
            {
                //循环查找指定字段
                if (ServerVars.CostCenterItemCostCenterID == xlsDataTable.Columns[i].ColumnName)
                    posiCostCenterID = i;
                else if (ServerVars.CostCenterItemMoneyValue == xlsDataTable.Columns[i].ColumnName)
                    posiMoneyValue = i;
                else if (ServerVars.CostCenterItemID == xlsDataTable.Columns[i].ColumnName)
                    costItemID = i;
            }
            if (posiCostCenterID < 0 || posiMoneyValue < 0 || costItemID < 0)
                throw new Exception("所提交的表格中,没有相对应的字段!请确认表格字段标题是否存在.");
            //List<TABC_JC_CostCenterItem> costCenterItems = new List<TABC_JC_CostCenterItem>();
            for (int i = 0; i < xlsDataTable.Rows.Count; i++)
            {
                TABC_JC_CostCenterItems cci = db.TABC_JC_CostCenterItems.Where(c => c.ID == Convert.ToInt32(xlsDataTable.Rows[i].ItemArray[costItemID])).Single();
                if (cci.作业中心ID != Convert.ToInt32(xlsDataTable.Rows[i].ItemArray[posiCostCenterID]))
                    throw new Exception("非法操作！无效的作业中心！");
                if (cci.成本细项ID != costItemsID)
                    throw new Exception("非法操作！无效的成本细项！");
                if (cci.会计期间ID != HttpContext.Current.Application[ServerVars.sysApplcationAccountPeriod].ToString())
                    throw new Exception("非法操作！无效的会计期间！");
                cci.金额 = Convert.ToDecimal(xlsDataTable.Rows[i].ItemArray[posiMoneyValue]);
            }

            //事务处理代码阶段
            if (db.Connection.State != ConnectionState.Open)
            {
                db.Connection.Open();
            }
            System.Data.Common.DbTransaction tran = db.Connection.BeginTransaction();
            db.Transaction = tran;
            try
            {
                //db.TABC_JC_CostCenterItems.InsertAllOnSubmit(costCenterItems);
                db.SubmitChanges();
                tran.Commit();
            }
            catch (Exception ex)
            {
                tran.Rollback();
                lastError = ex.Message;
                return -1;
            }
            return 0;
        }


        //作废函数
        /*
        public IEnumerable<TABC_JC_CostCenterItem> PreviewImportDataTable(DataTable xlsDataTable, string costItemsID)
        {
            int posiCostCenterID = -1;
            int posiMoneyValue = -1;

            if (xlsDataTable == null)
                throw new Exception("给出的数据表为NULL!");
            for (int i = 0; i < xlsDataTable.Columns.Count; i++)
            {
                if (ServerVars.CostCenterItemCostCenterID == xlsDataTable.Columns[i].ColumnName)
                    posiCostCenterID = i;
                else if (ServerVars.CostCenterItemMoneyValue == xlsDataTable.Columns[i].ColumnName)
                    posiMoneyValue = i;
            }
            if (posiCostCenterID < 0 || posiMoneyValue < 0)
                throw new Exception("所提交的表格中,没有相对应的字段!");
            List<TABC_JC_CostCenterItem> costCenterItems = new List<TABC_JC_CostCenterItem>();
            for (int i = 0; i < xlsDataTable.Rows.Count; i++)
            {
                TABC_JC_CostCenterItem cci = new TABC_JC_CostCenterItem();
                cci.金额 = Convert.ToDecimal(xlsDataTable.Rows[i].ItemArray[posiMoneyValue]);
                cci.作业中心ID = Convert.ToInt32(xlsDataTable.Rows[i].ItemArray[posiCostCenterID]);
                cci.成本细项ID = costItemsID;
                cci.会计期间ID = HttpContext.Current.Application[ServerVars.sysApplcationAccountPeriod].ToString();
                cci.公司ID = ServerVars.sysCompanyName;
                costCenterItems.Add(cci);
            }
            return costCenterItems;
        }
        */
    }
}
